package com.lanmaoly.concurrent;

/**
 * 交替打印奇偶数
 *
 * @author Administrator
 */
public class AlternatelyPrint {

    private static Object obj = new Object();
    private static int i = 0;

    public static void main(String[] args) {
//        try {
//            obj.wait();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        Thread threada = new Thread(() -> {
            try {
                while (i <= 10) {
                    synchronized (obj) {
                        System.out.println("tread a get obj look");
                        if (i % 2 == 1) {
                            obj.wait();
                        } else {
                            System.out.println(Thread.currentThread().getName() + ":" + i++);
                            obj.notify();
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "a");
        Thread threadb = new Thread(() -> {
            try {
                while (i <= 10) {
                    synchronized (obj) {
                        System.out.println("tread b get obj look");
                        if (i % 2 == 0) {
                            obj.wait();
                        } else {
                            System.out.println(Thread.currentThread().getName() + ":" + i++);
                            obj.notify();
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "b");
        threada.start();
        threadb.start();
    }
}
